package tech.wetech.admin3.controller;

import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.wetech.admin3.sys.exception.AooUserException;
import tech.wetech.admin3.sys.model.AooCompCertiData;
import tech.wetech.admin3.sys.model.AooUser;
import tech.wetech.admin3.sys.service.AooCompCertiDataService;
import tech.wetech.admin3.sys.service.AooPhoneCodeService;
import tech.wetech.admin3.sys.service.AooUserService;
import tech.wetech.admin3.sys.service.OssService;
import tech.wetech.admin3.util.CustomResponse;
import tech.wetech.admin3.util.GetDateUtil;
import tech.wetech.admin3.util.LianduAPIUtils;

import java.util.*;

@RestController
@RequestMapping("/oss")
public class AooCompCertiDataController {
  @Autowired
  private OssService ossService;
  @Autowired
  private AooCompCertiDataService aooCompCertiDataService;
  @Autowired
  private AooUserService aooUserService;
  @Autowired
  private AooPhoneCodeService phoneCodeService;
  @Autowired
  private LianduAPIUtils lianduAPIUtil;

  @Value("${liandu.api.personalVeriApi}")
  private String personalVeriApi;
  @Value("${liandu.api.companyVeriApi}")
  private String companyVeriApi;
  @Value("${liandu3ele}")
  private boolean liandu3ele;

  @Transactional
  @PostMapping("/auth-company")
  public ResponseEntity<?> authCompany(
    @RequestParam("email") String email,

    @RequestParam("companyName") String companyName,
    @RequestParam("creditCode") String creditCode,
    @RequestParam("legalRepresentativeName") String legalRepresentativeName,
    @RequestParam("legalRepresentativeID") String legalRepresentativeID,
    @RequestParam("companyAddress") String companyAddress,
    @RequestParam("applicantName") String applicantName,
    @RequestParam("applicantID") String applicantID,
    @RequestParam("applicantPhone") String applicantPhone,
    @RequestParam("verificationCode") String verificationCode,
    @RequestParam(value = "industryType", required = false) String industryType,

    @RequestParam("businessLicense") MultipartFile businessLicense,
    @RequestParam("authorization") MultipartFile authorization
  ) {
    boolean flag = phoneCodeService.verifyCode(applicantPhone, verificationCode);
    if (!flag) {
      return ResponseEntity.ok(new CustomResponse.r1("验证码错误或已过期", false, ""));
    }

    AooCompCertiData aooCompCertiData = new AooCompCertiData();

    aooCompCertiData.setEmail(email);
    aooCompCertiData.setCompanyName(companyName);
    aooCompCertiData.setCreditCode(creditCode);
    aooCompCertiData.setLegalRepresentativeName(legalRepresentativeName);
    aooCompCertiData.setLegalRepresentativeID(legalRepresentativeID);
    aooCompCertiData.setCompanyAddress(companyAddress);
    aooCompCertiData.setApplicantName(applicantName);
    aooCompCertiData.setApplicantID(applicantID);
    aooCompCertiData.setApplicantPhone(applicantPhone);
//    aooCompCertiData.setVerificationCode(verificationCode);
    aooCompCertiData.setIndustryType(industryType);
    aooCompCertiData.setCreateDate(GetDateUtil.getYyyyMMddHHmmss());
    if (!businessLicense.isEmpty()) {
      String businessLicenseUrl = ossService.uploadImage(businessLicense);
      aooCompCertiData.setBusinessLicenseUrl(businessLicenseUrl);
    }
    if (!authorization.isEmpty()) {
      String authorizationUrl = ossService.uploadImage(authorization);
      aooCompCertiData.setAuthorizationUrl(authorizationUrl);
    }
    aooCompCertiData.setStatus(1);  // 待审核


    // 企业三要素检验
    JSONObject responseJsonCom = lianduAPIUtil.companyThreeElementCheck(companyVeriApi, creditCode, companyName, legalRepresentativeName).join();
    System.out.println("企业三要素response-----" + responseJsonCom);
    boolean resultCom = "ok".equals(responseJsonCom.getStr("status"));
    // 个人三要素检验
    JSONObject responseJsonPer = lianduAPIUtil.personalThreeElementCheck(personalVeriApi, applicantID, applicantName, applicantPhone).join();
    System.out.println("个人三要素response-----" + responseJsonPer);
    boolean resultPer = "ok".equals(responseJsonPer.getStr("status"));

    if (!liandu3ele || resultCom) {
      if (!liandu3ele || resultPer) {
        AooUser user = aooUserService.findByEmail(email);
        if (user == null) {
          return ResponseEntity.ok(new CustomResponse.r1<>("认证邮箱和用户不匹配", false, null));
        }

        AooCompCertiData savedData = aooCompCertiDataService.save(aooCompCertiData);
        if (savedData != null && savedData.getId() != null) { // 假设savedData有一个ID字段来确认持久化

          user.setStatus(1);
          user.setVerifiedPhone(applicantPhone);

          return ResponseEntity.ok(new CustomResponse.r1<>("提交成功", true, savedData));
        } else {
          return ResponseEntity.ok(new CustomResponse.r1<>("企业和个人三要素验证通过，但提交失败", false, null));
        }
      } else {
        return ResponseEntity.ok(new CustomResponse.r1<>("申请人三要素未通过", false, responseJsonPer));
      }
    } else {
      return ResponseEntity.ok(new CustomResponse.r1<>("企业三要素未通过", false, responseJsonCom));
    }

  }

  @GetMapping("/get_comp_by_status")
  public ResponseEntity<?> getComByStatus(
    @RequestParam("status") Integer status
  ) {
    // 对newStatus的验证
    if (status < 0 || status > 3) {
      return ResponseEntity.badRequest().body(new CustomResponse.r1("status无效，只能为0, 1, 2 或3", false, null));
    }

    List<?> data = aooCompCertiDataService.findByStatus(status);

    Map<String, Object> resulet = new HashMap<>();
    resulet.put("total", data.size());
    resulet.put("record", data);
    return ResponseEntity.ok(new CustomResponse.r1<>("ok", true, resulet));
  }

  @GetMapping("/get_by_companyname")
  public ResponseEntity<?> getByCompanyName(@RequestParam("companyName") String companyName) {
    List<?> data = aooCompCertiDataService.findByCompanyNameContaining(companyName);
    if (data != null) {
      return ResponseEntity.ok(new CustomResponse.r1<>("ok", true, data));
    } else {
      throw new AooUserException("无记录");
    }
  }

  @GetMapping("/getall/comp")
  public ResponseEntity<?> getAllData(
    @RequestParam("page") int page,
    @RequestParam("size") int size
  ) {
    List<?> data = aooCompCertiDataService.getAllData();
    int total = data.size();
    int start = page * size;
    int end = Math.min(start + size, data.size());

    List<?> paginatedList;

    if (start < total) {
      paginatedList = data.subList(start, end);
    } else {
      paginatedList = new ArrayList<>();
    }

    Map<String, Object> result = new HashMap<>();
    result.put("page", page);
    result.put("size", size);
    result.put("total", total);
    result.put("record", paginatedList);

    return ResponseEntity.ok(new CustomResponse.r1<>("ok", true, result));
  }

  @Transactional
  @PutMapping("/reset/status-company")
  public ResponseEntity<?> resetStatus(
    @RequestParam("id") Integer id,
    @RequestParam("newStatus") Integer newStatus,
    @RequestParam(value = "checkDesc", required = false) String checkDesc
  ) {
    // 对newStatus的验证
    if (newStatus < 1 || newStatus > 3) {
      return ResponseEntity.badRequest().body(new CustomResponse.r1("状态值无效，只能为1, 2 或3", false, null));
    }
    boolean flag = aooCompCertiDataService.resetStatus(id, newStatus, checkDesc);

    if (flag) {
      return ResponseEntity.ok(new CustomResponse.r1<>("状态已更新", true, null));
    } else {
      return ResponseEntity.ok(new CustomResponse.r1<>("状态更新失败！", false, null));
    }
  }
}

